package com.stefan.verify;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

//method 1 to create a bean
//@Configuration
public class VerifyConfig {
    // 这里可以添加任何需要的配置
    // 例如，定义Bean或其他配置项

    // 如果需要，可以添加@Bean方法来定义特定的Bean
     @Bean
     public Check check() {
         ClassPathScanningCandidateComponentProvider provider =
             new ClassPathScanningCandidateComponentProvider(false);
         provider.addIncludeFilter(new AnnotationTypeFilter(StefanCheck.class));
         // 扫描指定包下的所有类
         Set<BeanDefinition> candidateComponents = provider.findCandidateComponents("com.stefan.verify");
         List<CheckDefinition> list = null;
         CheckDefinition checkDefinition = null;

        Check check = null;
         // 遍历找到的类
         if (!candidateComponents.isEmpty()) {
             list = new ArrayList<>();
             for (BeanDefinition candidateComponent : candidateComponents) {
                 try {
                     // 通过反射创建实例
                     Class<?> clazz = Class.forName(candidateComponent.getBeanClassName());
                     if (Check.class.isAssignableFrom(clazz)) {
                         StefanCheck annotation = clazz.getAnnotation(StefanCheck.class);
                         checkDefinition = new CheckDefinition();
                         checkDefinition.setSeq(annotation.value());
                         checkDefinition.setClazz(clazz);
                         list.add(checkDefinition);
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
             }
         }
         if (list != null && !list.isEmpty()) {
            // 按照seq排序
            Collections.sort(list);
            // 创建Check实例
            for (CheckDefinition definition : list) {
                try {
                    if (BaseCheck.class.isAssignableFrom(definition.getClazz())) {
                        check = (Check)  definition.getClazz().getDeclaredConstructor().newInstance();
                    } else {
                        check = (Check) definition.getClazz().getDeclaredConstructor(Check.class).newInstance(check);
                    }
                }catch (Exception e) {
                    System.out.println("Error creating Check instance: " + e.getMessage());
                }
            }
        }
        return check;
     }

}

